//调用app.js
const app = getApp()
import api from '../utils/api.js'
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function pZero(s) {
  return s < 10 ? '0' + s : s;
}
//时间
function forTime(number, format) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
  // untils.forTime(1488481383, 'Y-M-D h:m:s')
}
//缩略图
function getThumbnailUrl(originalfilePath, thumbnailWidth, thumbnailHeight, thumbnailType) {
  //先判断生成缩略图的三个重要条件是否存在
  if (null == originalfilePath || "" == originalfilePath || null == thumbnailWidth || "" == thumbnailWidth || null == thumbnailHeight || "" == thumbnailHeight) {
    return null;
  }
  //判断请求中是否还有"."用于截取后缀名
  if (originalfilePath.indexOf(".") == -1) {
    return null;
  }
  //获取后缀名
  var imgType = originalfilePath.substring(originalfilePath.lastIndexOf("."));
  //获取图片后缀名以外的路径
  var thumbnailPath = originalfilePath.replace(imgType, "");
  if (null != thumbnailType && "" != thumbnailType) {
    return app.globalData.baseThumbnailUrl + thumbnailPath + "=" + thumbnailWidth + "-" + thumbnailHeight + "+" + thumbnailType + imgType;
  } else {
    return app.globalData.baseThumbnailUrl + thumbnailPath + "=" + thumbnailWidth + "-" + thumbnailHeight + imgType;
  }

}


/**
 * oss方式处理图片缩略图
 * @param {*} url 图片的路径
 * @param {*} rw 图片缩放宽度
 * @param {*} rh 图片缩放高度
 * @param {*} cw 图片裁剪宽度
 * @param {*} ch 图片裁剪高度
 * @param {*} cg 图片裁剪位置 默认为center: 中间   north：中上
 */
function ossBaseImghandler(url, rw, rh, cw, ch, cg = 'center') {
  if (!url || url.includes("x-oss-process")) {
    return url
  }
  return `${app.globalData.ossImgBaseUrl}${url}?x-oss-process=image/resize,w_${rw},h_${rh},m_mfit,limit_0/crop,w_${cw},h_${ch},g_${cg}`
}

/**
 * 使用别名访问oss
 */
function ossBaseImghandler_style(url, style) {
  if (!url || url.includes("x-oss-process")) {
    return url
  }
  return `${app.globalData.ossImgBaseUrl}${url}?x-oss-process=style${style&&'/' + style}`
}

/**
 * 原图片显示
 * @param {*} url 图片的路径
 */
function ossBaseImghandler_0(url) {
  return `${app.globalData.ossImgBaseUrl}${url}`
}

/**
 * 裁剪1:1居中显示
 * @param {*} url 图片的路径
 * @param {*} w 裁剪图片的尺寸
 */
function ossBaseImghandler_1_1(url, w) {
  return ossBaseImghandler(url, w, w, w, w)
}

function ossBaseImghandler_3_2(url, w, h, cg = 'north') {
  return ossBaseImghandler(url, w, h, w, h, cg)
}

function getImgHeight(width, height) {
  return parseInt(height / (width / 600))
}
//数组去重
function unique(arr) {
  for (var i = 0; i < arr.length; i++) {
    for (var j = i + 1; j < arr.length; j++) {
      if (arr[i] == arr[j]) {
        arr.splice(j, 1);
        j--;
      }
    }
  }
  return arr;
}
//计算器

function calculation(type, num1, num2) {
  var temp1, temp2, a;
  try {
    // 获取temp1小数点后的长度
    temp1 = num1.toString().split(".")[1].length;
  } catch (e) {
    temp1 = 0;
  }
  try {
    // 获取temp2小数点后的长度
    temp2 = num2.toString().split(".")[1].length;
  } catch (e) {
    temp2 = 0;
  }
  // Math.max(temp1, temp2) 为了获取temp1和temp2两个值中较大的一个
  // Math.pow(a,b) 表示 a 的 b 次方
  a = Math.pow(10, Math.max(temp1, temp2));

  // 计算的方式是先将所有的小数乘为整数，待加减运算执行完之后再除去对应的 a 的值，将其变为小数输出
  // 先判断执行的方式是否是加法，不是的话则执行减法运算
  return type == "add" ? (num1 * a + num2 * a) / a : (num1 * a - num2 * a) / a;
}

// 获取手机号
function getWxPhone(encryptedData, iv) {
  let getPhone = '/system/wechatRegisterController/getPhone'
  let getSmartUnionId = '/base/wechatAppletsController/getSmartUnionId'
  //监测登录是否过期
  return new Promise((resolve, reject) => {
      wx.checkSession({
          success(res) {
              api.post(getPhone, {
                  encryptedData,
                  iv,
                  key: app.data.key
              }).then(res => {
                  resolve(res.data.data)
              })
          },
          fail(res) {
              wx.login({
                  success: (res) => {
                      api.post(getSmartUnionId, {
                          appId: 18,
                          code: res.code
                      }).then(res => {
                          app.data.key = res.data.data.key
                          api.post(getPhone, {
                              encryptedData,
                              iv,
                              key: app.data.key
                          }).then(res => {
                              resolve(res.data.data)
                          })
                      })
                  },
                  fail(err) {
                      reject(err)
                  }
              })
          }
      })
  })
}
module.exports = {
  formatTime: formatTime,
  forTime: forTime,
  getThumbnailUrl: getThumbnailUrl,
  getImgHeight: getImgHeight,
  pZero: pZero,
  unique: unique,
  calculation: calculation,
  ossBaseImghandler,
  ossBaseImghandler_style,
  ossBaseImghandler_0,
  ossBaseImghandler_1_1,
  ossBaseImghandler_3_2,
  getWxPhone
}